package bancosys.tec.services.input.driver.xml;

import java.util.Iterator;
import java.util.Map;

import jmine.tec.services.io.ServiceBean;
import jmine.tec.services.io.ServicesPageBean;
import jmine.tec.utils.io.EncodingUtils;
import bancosys.tec.datadigester.DigesterDriver;
import bancosys.tec.datadigester.DigesterFile;
import bancosys.tec.services.input.XLSFileConstants;
import bancosys.tec.services.input.driver.bean.ServicePageHeader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * Driver para leitura de serviços escritos em um arquivo XML.
 * 
 * @author Rafael Volpato
 */
public class ServiceXMLDriver implements DigesterDriver<ServicePageHeader> {

    /**
     * Parseia o arquivo XML.
     * 
     * @param file file
     * @param props propriedades para parse dos drivers
     * @return servicePageHeader com os dados do arquivo
     */
    public ServicePageHeader parse(DigesterFile file, Map<String, String> props) {
        // Instanciar/Configurar o XStream
        String domDriverCharset = props.get("input.encoding");

        if(domDriverCharset == null) {
            domDriverCharset = EncodingUtils.UTF_CHARSET;
        }
        
        XStream xStream = new XStream(new DomDriver(domDriverCharset));
        xStream.autodetectAnnotations(true);
        xStream.alias("importacao", ServicePageHeader.class);
        xStream.alias("services", ServicesPageBean.class);
        xStream.alias("service", ServiceBean.class);

        // Converter o arquivo XML em um objeto do tipo ServicePageHeader
        final ServicePageHeader header = (ServicePageHeader) xStream.fromXML(file.getInputStream());
        Iterator<ServicesPageBean> iterator = header.getWorkSheets().iterator();
        while(iterator.hasNext()) {
            final String name = iterator.next().getName();
            if(name != null && name.startsWith(XLSFileConstants.IGNORE_SHEET_PREFIX)) {
                iterator.remove();
            }
        }
        return header;
    }

}
